<?php

namespace app\common\lib\live;


use app\chat\LiveMessage;
use app\common\cachemodel\live\LiveAwardAcitveRecord;
use app\common\cachemodel\live\LiveAwardResultUser;
use app\common\cachemodel\live\LiveCouponActiveRecord;
use app\common\cachemodel\live\LiveUserGiftBag;
use app\common\cachemodel\live\LiveUserGiftBagRecord;
use app\common\cachemodel\UserCoupon;
use app\common\cachemodel\ZlCouponAttr;
use app\common\lib\SensorsData;
use app\common\model\Goods;
use think\Db;
use think\Log;
use think\queue\Job;

class LiveDrawALotteryJob
{
    /**
     * 直播间 抽奖活动 开奖
     * @param Job $job
     * @param $jobData
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function task(Job $job, $jobData)
    {
        $jobAttempts = $job->attempts();
        if ($jobAttempts > 1)
        {
            $job->delete();
            return;
        }

        if (isset($jobData['type']) && $jobData['type'] === 'close_coupon_active')
        {
            // $jobData = [
            //     'type' => 'close_coupon_active',
            //     'coupon_acitve_id' => 1,
            // ];
            $this->closeCouponActiveJob($jobData);
            $job->delete();
            return;
        }
        // $jobData = [
        //     'award_acitve_id' => 1,
        // ];

        $activeInfo = (new LiveAwardAcitveRecord())->getInfoById($jobData['award_acitve_id']);

        if ($activeInfo && $activeInfo['status'] == 1)
        {
            try
            {
                // 抽取幸运用户
                try
                {
                    $awardUsers = Db::table('`live_data`.live_award_active_user_' . $activeInfo['live_record_id'])->where('award_acitve_id', $jobData['award_acitve_id'])->column('uid');
                }
                catch (\Exception $e)
                {
                    Log::write("直播间抽奖活动结算异常，活动ID「{$jobData['award_acitve_id']}」：错误消息：{$e->getMessage()};File:{$e->getFile()};Line:{$e->getLine()}", 'error', true);
                    $awardUsers = [];
                }

                $uids = [];
                if (!empty($awardUsers))
                {
                    if (count($awardUsers) > $activeInfo['num'])
                    {
                        $awardUsers = array_flip($awardUsers);

                        $uids = array_rand($awardUsers, $activeInfo['num']);

                        if (!is_array($uids))
                        {
                            $uids = [$uids];
                        }
                    } else
                    {
                        $uids = $awardUsers;
                    }
                }

                $userInfo = [];
                if ($uids)
                {
                    $userInfo = Db::table('wechat_backup_07_18_14_43_00.app_user')->whereIn('id', $uids)->column('nickname', 'id');
                }

                $data = [];
                $time = time();
                foreach ($uids as $uid)
                {
                    if ($activeInfo['award_type'] == 1) // 奖品类型  1=>礼物 2=>优惠券
                    {
                        (new LiveUserGiftBag())->sendUserGift((int)$uid, $activeInfo['award_cid']);// 发放奖品
                        // 添加变动记录
                        $record = [
                            'uid' => $uid,
                            'gid' => $activeInfo['award_cid'],
                            'flag' => 3,
                            'flag_type' => 0,
                            'live_record_id' => $activeInfo['live_record_id'],
                            'live_id' => $activeInfo['live_id'],
                            'change_num' => 1,
                            'create_time' => $time,
                        ];
                        (new LiveUserGiftBagRecord())->saveData($uid, $record);
                    } else
                    {    // 发放优惠券
                        $couponInfo = (new ZlCouponAttr())->getInfoById($activeInfo['award_cid'], ['ur_id', 'gids', 'type', 'desc']);

                        $cData = [
                            'uid' => $uid,
                            'c_id' => $activeInfo['award_cid'],
                            'ur_id' => $couponInfo['ur_id'],
                            'start_time' => $time,
                            'end_time' => strtotime("+{$activeInfo['coupon_expire_time']} hours", $time),
                            'give_time' => $time,
                            'status' => 0,
                            'price' => 0,
                            'is_give' => 0,
                            'live_id' => $activeInfo['live_id'],
                            'create_time' => $time,
                            'update_time' => 0,
                        ];
                        $userCouponModel = new UserCoupon();

                        // 写入用户卡券中心
                        $userCouponModel->allowField(true)->save($cData);
                        $ucId = $userCouponModel->id;
                        // 更新用户卡券中心缓存
                        $userCouponModel->listDataAdd($uid, [$ucId => $ucId], 1);
                        // 神策打点
                        $gidsArr = explode(',', $couponInfo['gids']);
                        $couponInfo['couponRangeArr'] = (new Goods())->where('id', 'in', $gidsArr)->column('name');
                        // 神策打点 75 获得优惠券 AcquireCoupon
                        SensorsData::track($uid, true, 'AcquireCoupon', [
                            'refer_name' => '',
                            'refer_link' => '',
                            'coupon_name' => $couponInfo['desc'],
                            'coupon_expire' => date('Y-m-d H:i:s', $cData['end_time']),
                            'coupon_type' => $userCouponModel->couponTypeName[$couponInfo['type']],
                            'coupon_range' => $couponInfo['couponRangeArr'],
                            'acquire_channel' => "直播间【{$activeInfo['live_id']}】抽奖活动ID【{$jobData['award_acitve_id']}】",
                            'is_give' => false,
                            'acquire_scene' => '直播间抽奖活动',
                        ]);
                    }

                    $data[] = [
                        'live_id' => $activeInfo['live_id'],
                        'live_record_id' => $activeInfo['live_record_id'],
                        'award_acitve_id' => $jobData['award_acitve_id'],
                        'uid' => $uid,
                        'create_time' => $time,
                    ];

                    // 直播抽奖中奖
                    $sensorsTrackData = [   // 神策打点数据
                        'hoster_name' => $anchInfo['name'] ?? '',
                        'live_id' => $activeInfo['live_id'],
                        'live_record_id' => $activeInfo['live_record_id'],
                        'award_name' => $activeInfo['award_name'],  // 奖品名称
                        'award_username' => $userInfo[$uid] ?? '',    // 中奖用户昵称
                    ];  // 中奖打点
                    SensorsData::track($uid, true, 'LiveAwardResult', $sensorsTrackData);

                }

                // 活动结束
                (new LiveAwardAcitveRecord())->updateData($jobData['award_acitve_id'], ['status' => 2], 30);

                if ($uids)
                {
                    // 记录中奖用户
                    (new LiveAwardResultUser())->saveAll($data);
                    // 发送抽奖结果信息
                    $res = Db::table('wechat_backup_07_18_14_43_00.app_user')->whereIn('id', $uids)->field('uen,nickname')->select();
                } else
                {
                    $res = [];
                }

                LiveMessage::sendMsg(LiveMessage::who(LiveMessage::WHO_TYPE_ALL, $activeInfo['live_id'], $activeInfo['live_id']), LiveMessage::MSG_TYPE_POP_AWARD_END, [
                    'id' => $jobData['award_acitve_id'],
                    'award_name' => $activeInfo['award_name'],
                    'continue_second' => 30,
                    'award_users' => $res,
                    'target' => 'local',
                    'link' => $activeInfo['award_type'] == 1 ? "live_gift_position?id={$activeInfo['award_cid']}&need_auth=0" : 'discount_coupon_center?need_auth=2',
                ]);

                (new LiveAwardAcitveRecord())->rmListCache($activeInfo['live_id']);
            }
            catch (\Exception $e)
            {
                Log::write("直播间抽奖活动结算失败，活动ID「{$jobData['award_acitve_id']}」：错误消息：{$e->getMessage()};File:{$e->getFile()};Line:{$e->getLine()}", 'error', true);
            }
        }

        $job->delete();
    }

    private function closeCouponActiveJob($data)
    {
        try
        {
            (new LiveCouponActiveRecord())->updateData($data['coupon_acitve_id'], ['status' => 2]);
        }
        catch (\Exception $e)
        {
            Log::write("直播间抢优惠券活动关闭失败，活动ID「{$data['coupon_acitve_id']}」：错误消息：{$e->getMessage()};File:{$e->getFile()};Line:{$e->getLine()}", 'error', true);
        }
    }
}
